package com.hong.qrpc.client;

import com.hong.qrpc.Peer;
import com.hong.qrpc.TransportClient;
import lombok.ToString;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author HQT
 * @Date 2022/7/10 9:56
 */
@ToString
public class HttpTransportClient implements TransportClient {
    private String url;
    private Peer helpCompare;

    /**
     * 创建连接，并且在完成之后唤醒等待的线程
     *
     * @param peer 网络端点对象
     */
    @Override
    public void connect(Peer peer) {
        this.helpCompare = peer;
        this.url = new StringBuilder().append("http://").append(peer.getHost()).
                append(":").append(peer.getPort()).toString();
        synchronized (peer) {
            peer.notifyAll();
        }
    }

    /**
     * 写入数据
     *
     * @param data 写入的数据
     * @return 响应的数据
     */
    @Override
    public InputStream write(InputStream data, int serializationType, long timeout) {
        try {
            //创建一个连接
            HttpURLConnection httpConn = (HttpURLConnection) new URL(url).openConnection();
            //设置连接的一些属性
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);
            httpConn.setRequestMethod("POST");
            httpConn.addRequestProperty("serializationType", String.valueOf(serializationType));
            //如果超时时间小于一的话就默认超时时间为无限长
            if (timeout < 1) {
                httpConn.setReadTimeout((int) Math.min(Integer.MAX_VALUE, timeout));
            }
            httpConn.connect();
            IOUtils.copy(data, httpConn.getOutputStream());
            int resultCode = httpConn.getResponseCode();
            if (resultCode == HttpURLConnection.HTTP_OK) {
                return httpConn.getInputStream();
            } else {
                return httpConn.getErrorStream();
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * 关闭连接，用的是http短连接，所以不需要关闭
     */
    @Override
    public void close() {

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        HttpTransportClient that = (HttpTransportClient) o;

        return helpCompare.equals(that.helpCompare);
    }

    @Override
    public int hashCode() {
        return helpCompare.hashCode();
    }
}
